<template>
  <div>
    <!-- 筛选条件 -->
    <SearchFrom
      ref="formCardRef"
      :addConfigFields="addDeptFilter"
      :filterFields="deptFilter"
      v-model="queryParams"
      @search="handleSearch"
      @reset="handleReset"
    >
    </SearchFrom>
    <div class="p-2">
      <el-card shadow="hover">
        <!-- 表格 -->
        <TableWrapper
          id="deptTable"
          :height="tableHeight"
          showToolbar
          :tableList="deptList"
          :columns="columns"
          :tableLoading="tableLoading"
          :total="total"
          :treeConfig="{
            transform: true,
            rowField: 'deptId',
            parentField: 'parentId'
          }"
          :queryParams="queryParams"
          @pagination="getList"
          :actionWidth="80"
        >
          <!-- 左侧按钮 -->
          <template #toolbar>
            <el-button @click="handleAdd()" type="primary">添加部门 </el-button>
            <el-button @click="handleToggleExpandAll" plain>展开/折叠</el-button>
          </template>
          <!-- 操作 -->
          <template #action="{ row }">
            <el-button link size="small" type="primary" @click="handleUpdate(row)">修改</el-button>
            <el-button link size="small" type="primary" @click="handleAdd(row)"> 新增 </el-button>
            <el-button link size="small" type="primary" @click="handleDelete(row)">删除</el-button>
          </template>
        </TableWrapper>
      </el-card>
      <!-- 对话框 -->
      <DialogWapper :loading="loading" v-model="dialog.visible" :title="dialog.title" @confirm="submitForm" @cancel="cancel">
        <el-form ref="deptFormRef" :model="form" :rules="rules" label-width="80px">
          <el-row>
            <el-col v-if="form.parentId !== 0" :span="24">
              <el-form-item label="上级部门" prop="parentId">
                <el-tree-select
                  v-model="form.parentId"
                  :data="deptOptions"
                  :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                  value-key="deptId"
                  placeholder="选择上级部门"
                  check-strictly
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="部门名称" prop="deptName">
                <el-input v-model="form.deptName" placeholder="请输入部门名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="类别编码" prop="deptCategory">
                <el-input v-model="form.deptCategory" placeholder="请输入类别编码" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="显示排序" prop="orderNum">
                <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="负责人" prop="leader">
                <el-select v-model="form.leader" placeholder="请选择负责人">
                  <el-option v-for="item in deptUserList" :key="item.userId" :label="item.userName" :value="item.userId" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="phone">
                <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="部门状态">
                <el-radio-group v-model="form.status">
                  <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </DialogWapper>
    </div>
  </div>
</template>

<script setup name="Dept">
import { deptFilter, addDeptFilter } from '@/apo/system-filter-config';
import { listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild } from '@/api/system/dept';
import useTableHeight from '@/hooks/useTableHeight';
import { listUserByDeptId } from '@/api/system/user';
const formCardRef = ref();
const { showSearch, tableHeight } = useTableHeight(formCardRef, 150);
const { proxy } = getCurrentInstance();
const { sys_normal_disable } = toRefs(proxy?.useDict('sys_normal_disable'));
const columns = ref([
  { field: 'deptName', title: '部门名称', treeNode: true },
  { field: 'deptCategory', title: '类别编码' },
  { field: 'orderNum', title: '排序' },
  { field: 'status', title: '状态' },
  { field: 'createTime', title: '创建时间' }
]);
const total = ref(0);
const tableLoading = ref(false);
const deptList = ref([]);
const loading = ref(true);
const deptOptions = ref([]);
const isExpandAll = ref(true);
const deptUserList = ref([]);
const dialog = reactive({
  visible: false,
  title: ''
});
const deptTableRef = ref();
const queryFormRef = ref();
const deptFormRef = ref();
const initFormData = {
  deptId: undefined,
  parentId: undefined,
  deptName: undefined,
  deptCategory: undefined,
  orderNum: 0,
  leader: undefined,
  phone: undefined,
  email: undefined,
  status: '0'
};
const initData = {
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptName: undefined,
    deptCategory: undefined,
    status: undefined
  },
  rules: {
    parentId: [{ required: true, message: '上级部门不能为空', trigger: 'blur' }],
    deptName: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
    orderNum: [{ required: true, message: '显示排序不能为空', trigger: 'blur' }],
    email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
    phone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }]
  }
};
const data = reactive(initData);

const { queryParams, form, rules } = toRefs(data);

/** 查询菜单列表 */
const getList = async () => {
  loading.value = true;
  const res = await listDept(queryParams.value);
  deptList.value = res.data;
  loading.value = false;
};

/** 查询当前部门的所有用户 */
async function getDeptAllUser(deptId) {
  if (deptId !== null && deptId !== '' && deptId !== undefined) {
    const res = await listUserByDeptId(deptId);
    deptUserList.value = res.data;
  }
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};
/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  deptFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  toggleExpandAll(deptList.value, isExpandAll.value);
};
/** 展开/折叠所有 */
const toggleExpandAll = (data, status) => {
  data.forEach((item) => {
    deptTableRef.value?.toggleRowExpansion(item, status);
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status);
  });
};

/** 新增按钮操作 */
const handleAdd = async (row) => {
  reset();
  const res = await listDept();
  const data = proxy?.handleTree(res.data, 'deptId');
  if (data) {
    deptOptions.value = data;
    if (row && row.deptId) {
      form.value.parentId = row?.deptId;
    }
    dialog.visible = true;
    dialog.title = '添加部门';
  }
};

/** 修改按钮操作 */
const handleUpdate = async (row) => {
  reset();
  //查询当前部门所有用户
  getDeptAllUser(row.deptId);
  const res = await getDept(row.deptId);
  form.value = res.data;
  const response = await listDeptExcludeChild(row.deptId);
  const data = proxy?.handleTree(response.data, 'deptId');
  if (data) {
    deptOptions.value = data;
    if (data.length === 0) {
      const noResultsOptions = {
        deptId: res.data.parentId,
        deptName: res.data.parentName,
        children: []
      };
      deptOptions.value.push(noResultsOptions);
    }
  }
  dialog.visible = true;
  dialog.title = '修改部门';
};
/** 提交按钮 */
const submitForm = () => {
  deptFormRef.value?.validate(async (valid) => {
    if (valid) {
      form.value.deptId ? await updateDept(form.value) : await addDept(form.value);
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};
/** 删除按钮操作 */
const handleDelete = async (row) => {
  await proxy?.$modal.confirm('是否确认删除名称为"' + row.deptName + '"的数据项?');
  await delDept(row.deptId);
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

onMounted(() => {
  getList();
});
const handleSearch = (val) => {
  getList();
};
const handleReset = () => {
  queryParams.value = {};
  getList();
};
</script>
